import 'dart:convert';
import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:rtmp_publisher/camera.dart';
import 'dart:async';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../main.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:exams_app/widget/hexcolor.dart';

import 'package:exams_app/home_module/exams_module/logic.dart';

class DevicePage extends StatefulWidget {
  @override
  _DevicePageState createState() => _DevicePageState();
}

class _DevicePageState extends State<DevicePage> {

  HomeModuleLogic logic = Get.put(HomeModuleLogic());

  var imageFile0;

  var stateStr = '';
  var permissionStr = '';


  var showmake = false;

  CameraController controller;


  // void initCamers() async {
  //   WidgetsFlutterBinding.ensureInitialized();
  //   final cameras = await availableCameras();
  //   controller = CameraController(cameras[1], ResolutionPreset.medium);
  //
  //   controller.initialize().then((_) {
  //     if (!mounted) {
  //       return;
  //     }
  //     setState(() {});
  //   });
  //
  //
  // }

  @override
  void initState() {
    // TODO: implement initState
    requestPermission();
    super.initState();
    // initCamers();

    controller = CameraController(cameras[1], ResolutionPreset.medium);

    controller.initialize().then((_) {
      if (!mounted) {

        return;
      }
      permissionStr = '视频录制正常，拍照功能正常';
      setState(() {});
    });



  }

  /// 权限检测
  Future requestPermission() async {
    // Get.dialog(
    //   Center(
    //       child: Material(
    //     type: MaterialType.transparency,
    //     child: Container(
    //       height: 5,
    //       width: 230,
    //       child: new LinearProgressIndicator(
    //         backgroundColor: Colors.blue,
    //         // value: 0.2,
    //         valueColor: new AlwaysStoppedAnimation<Color>(Colors.red),
    //       ),
    //     ),
    //   )),
    // );


    // 申请结果

    PermissionStatus permission =
    await PermissionHandler().checkPermissionStatus(PermissionGroup.camera);

    if (permission == PermissionStatus.granted) {
      Future.delayed(Duration(seconds: 0), () {
        BotToast.showText(text: '视频录制正常，拍照功能正常');
        //1秒后这个i行
    Future.delayed(Duration(milliseconds: 3000), () {
//代码省略
      savaPic();


    });
        // permissionStr = '视频录制正常，拍照功能正常';
      });
    } else {
      BotToast.showText(text: '权限申请被拒绝,请到隐私打开相机权限');
      Future.delayed(Duration(seconds: 0), () async {
        permissionStr = '权限申请被拒绝,请到隐私打开相机权限';
        // bool isOpened = await PermissionHandler().openAppSettings();
      });
      // Fluttertoast.showToast(msg: "权限申请被拒绝");

    }
  }
  /// 自动识别
  void savaPic()async{

    String timestamp() =>
        DateTime.now().millisecondsSinceEpoch.toString();
    if (!controller.value.isInitialized) {
      print('Error: select a camera first.');
      permissionStr = '视频录制正常，拍照功能正常';
      return null;
    }
    // getApplicationDocumentsDirectory  文档目录
    final Directory extDir =
    await getApplicationDocumentsDirectory();
    final String dirPath =
        '${extDir.path}/Pictures/flutter_test';
    print(dirPath);
    await Directory(dirPath).create(recursive: true);
    final String filePath = '$dirPath/${timestamp()}.jpg';
    print(filePath);
    // imageFile0 = filePath;
    // if (controller.value.isTakingPicture) {
    //   // A capture is already pending, do nothing.
    //   print('E1111');
    //   return null;
    // }

    try {
      imageFile0 = filePath;
      await controller.takePicture(filePath);

      // XFile file = await controller.takePicture();
      // imageFile0 = file.path;
      print('保存成功');
      var imageys = await imageCompressAndGetFile(File(imageFile0));

      List bytes = await imageys.readAsBytes();

      String bs64 = base64Encode(bytes);

      String bs64Image = 'data:image/jpg;base64,${bs64}';

      logic.requestDataWithAIface(bs64Image).then((value) {

        showmake = true;

        if(value['errcode']==-100){
          // BotToast.showText(text: value['message']);
          BotToast.showText(text: '摄像头内未检测到人脸');
          stateStr = '摄像头内未检测到人脸';
          setState(() {

          });
        }else if(value['data']=='False'){
          BotToast.showText(text: '检测到不是本人');
          stateStr = '检测到不是本人';
          setState(() {

          });
        }else if(value['data']=='True'){
          BotToast.showText(text: '人脸检测成功');
          stateStr = '人脸检测成功';
          setState(() {

          });

        }
        else{
          print('未知');
          stateStr = '未知';
          setState(() {

          });
          BotToast.showText(text: '未知');
        }


      });



      setState(() {

      });
      // Get.to(DisplayPictureScreen(
      //   imagePath: file.path,
      // ));
    } on CameraException catch (e) {
      print('保存失败');
      print(e);
      return null;
    }
  }

  @override
  void dispose() {
    controller.dispose();
    // TODO: implement dispose
    super.dispose();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          TextButton(onPressed: (){
            savaPic();
          }, child: Text('重新检测',style: TextStyle(color: Colors.white),))
        ],
        title: Text('设备检测'),
      ),
      body: Stack(
        children: [
          Align(
              alignment: Alignment.topCenter,
              child:  !controller.value.isInitialized?Container(
                child: Text('错误信息:未检测到摄像头'),
              ):AspectRatio(
                aspectRatio: controller.value.aspectRatio,
                child: Container(
                  margin: EdgeInsets.all(5),
                  clipBehavior: Clip.antiAliasWithSaveLayer,
                  // color: Colors.red,
                  //边框设置
                  decoration: new BoxDecoration(

                    shape: BoxShape.circle,
                  ),

                  // height: 500,
                  child: CameraPreview(
                    controller,
                  ),
                ),
              )
          ),
          Align(
            child: !controller.value.isInitialized?Container(margin: EdgeInsets.only(bottom: 100),
              child: Text('提示：请到-设置-权限管理打开相机权限'),
            ): Container(
              alignment: Alignment.bottomCenter,
              // color: Colors.red,
              child: Column(
                mainAxisAlignment:MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                 Visibility(child:  Row(
                   mainAxisAlignment: MainAxisAlignment.center,
                   children: [
                     stateStr=='人脸检测成功'?Icon(Icons.check,color: Theme.of(context).primaryColor,):Icon(Icons.error_outline_sharp,color: Colors.red,),
                     Text('${stateStr}',style: TextStyle(color: stateStr=='人脸检测成功'?Colors.black:Colors.red ),),
                   ],
                 ),visible: showmake,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.check,color: Theme.of(context).primaryColor,),
                      Text('${permissionStr}'),
                    ],
                  ),
                ],
              ),
              margin: EdgeInsets.only(bottom: 100),
            ),
            alignment: Alignment.bottomCenter,
          )
        ],
      )
    );
  }
}
